<?php
/*
 * 数据库操作类
 */
class Library_Database {
    
    private static $dbh;
    private static $statement;
    private static $strdbset = "";
    private static $arrdbset=array();

    /*
     * 载入数据库配置信息，保存数据库连接
     */
    public static function load($dbsetting='default')
    {
        static $obj;
        
        if(array_key_exists($dbsetting, self::$arrdbset) && self::$arrdbset[$dbsetting] && self::$arrdbset[$dbsetting]["obj"])
        {
            $obj = self::$arrdbset[$dbsetting]["obj"];
        }
        else
        {
            $Config_db = Config::get('db');
            $dbconfig = $Config_db[$dbsetting];
            
            $dsn = "mysql:dbname={$dbconfig['dbname']};host={$dbconfig['host']}";
            $dbh = new PDO($dsn, $dbconfig['username'], $dbconfig['password'], array(PDO::MYSQL_ATTR_INIT_COMMAND=>"SET NAMES 'utf8';"));
            self::$arrdbset[$dbsetting]["dbh"] = $dbh;
        
            $obj = new Library_Database($dbsetting);
            self::$arrdbset[$dbsetting]["obj"] = $obj;
        }
        
        self::$strdbset = $dbsetting;
        
        return $obj;
    }

    /**
     * 执行数据库操作;
     * 
     * 当develop为true时，执行错误将打印到页面上;
     * 
     * 当develop为false时，执行错误将打印到log日志中;
     * 
     */
    public function query($sql, $prepare=array())
    {
        $statement = self::$arrdbset[self::$strdbset]["dbh"]->prepare($sql);
        
        if(!$statement->execute($prepare))
        {
            throw new Exception("QUERY SQL:" . $sql);
            throw new Exception("QUERY ERROR:" . json_encode($statement->errorInfo()));
            return false;
        }
        
        self::$statement = $statement;
        
        return true;
    }

    /*
     * 取得多行记录集
     */
    public function fetch_all()
    {
        return self::$statement->fetchAll(PDO::FETCH_ASSOC);
    }

    /*
     * 取得单行记录
     */
    public function fetch_row()
    {
        return self::$statement->fetch(PDO::FETCH_ASSOC);
    }
    
    /*
     * 得到影响行数
     */
    public function rowcount()
    {
        return self::$statement->rowCount();
    }
    
    /*
     * 得到最后插入ID
     */
    public function getLastInsertId()
    {
        return self::$arrdbset[self::$strdbset]["dbh"]->lastInsertId();
    }
    
    /*
     * 开始事务
     */
    public function beginTransaction() {
        self::$arrdbset[self::$strdbset]["dbh"]->beginTransaction();
    }
    
    /*
     * 提交事务
     */
    public function commitTransaction() {
        self::$arrdbset[self::$strdbset]["dbh"]->commit();
    }
    
    /*
     * 回滚事务
     */
    public function rollBackTransaction() {
        self::$arrdbset[self::$strdbset]["dbh"]->rollBack();
    }
}
?>